package io.bdmc.common.http;

import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.Header;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class HttpClientUtil {

    private static final Logger logger = LoggerFactory.getLogger((HttpClientUtil.class));

    @Autowired
    private CloseableHttpClient httpClient;

    @Autowired
    private RequestConfig config;

    /**
     * 不带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     * 
     * @param url
     * @return
     * @throws Exception
     */
    public HttpResult doGet(String url, Header[] headers) throws Exception {
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response =null;
        try{
            httpGet.setHeaders(headers);
            httpGet.setConfig(config);
            logger.info("GET请求地址：" + url);
            response = this.httpClient.execute(httpGet);
            HttpResult result = new HttpResult(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity()));
            logger.info("GET响应状态码：" + result.getCode() + "。内容：" + result.getBody());
            return result;
        }finally{
            if (response != null) {
                response.close();
              }
        }
      
    }

    /**
     * 
     * @param url     请求地址，包含参数，因为有些是浏览器地址后面直接加id，有些是?id=xxx
     * @param headers 请求头
     * @return
     * @throws Exception
     */
    public HttpResult doDelete(String url, Header[] headers) throws Exception {
        HttpDelete httpDelete = new HttpDelete(url);
        CloseableHttpResponse response =null;
        try{
            httpDelete.setHeaders(headers);
            httpDelete.setConfig(config);
            logger.info("DELETE请求地址：" + url);
            response = this.httpClient.execute(httpDelete);
            HttpResult result = new HttpResult(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity(), "UTF-8"));
            logger.info("DELETE响应状态码：" + result.getCode() + "。内容：" + result.getBody());
            return result;
        }finally{
            if (response != null) {
                response.close();
              }
        }
        
    }

    /**
     * 带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     * 
     * @param url
     * @return
     * @throws Exception
     */
    public HttpResult doGet(String url, Map<String, Object> map, Header[] headers) throws Exception {
        String newurl = buildGetParams(url, map);
        // 调用不带参数的get请求
        return this.doGet(newurl, headers);
    }

    // 拼接get参数
    public String buildGetParams(String url, Map<String, Object> map) throws URISyntaxException {
        URIBuilder uriBuilder = new URIBuilder(url);

        if (map != null) {
            // 遍历map,拼接请求参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }
        return uriBuilder.build().toString();
    }

    /**
     * 组装头部信息
     * 
     * @param headers
     * @return
     */
    private Header[] assemblyHeader(Map<String, String> headers) {
        Header[] allHeader = new BasicHeader[headers.size()];
        int i = 0;
        for (String str : headers.keySet()) {
            allHeader[i] = new BasicHeader(str, headers.get(str));
            i++;
        }
        return allHeader;
    }

    /**
     * 带参数的post请求
     * 
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public HttpResult doPost(String url, String jsonParam, Header[] headers) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            // 加入配置信息
            httpPost.setConfig(config);
            httpPost.setHeaders(headers);
            logger.info("POST请求地址" + url);

            if (jsonParam != null) {
                StringEntity entity = new StringEntity(jsonParam, "utf-8");// 解决中文乱码问题
                httpPost.setEntity(entity);
                logger.info("POST请求参数：" + jsonParam.toString());
            }
            // 发起请求
            response = this.httpClient.execute(httpPost);
            HttpResult result = new HttpResult(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity()));
            logger.info("POST响应状态码：" + result.getCode() + "。内容：" + result.getBody());
            return result;
        } finally {
            if (response != null) {
                response.close();
              }
        }

    }

    /**
     * 不带参数post请求
     * 
     * @param url
     * @return
     * @throws Exception
     */
    public HttpResult doPost(String url, Header[] headers) throws Exception {
        return this.doPost(url, null, headers);
    }

    /**
     * 带参数 发起 json post请求
     * 
     * @param url,jsonParam
     * @return
     * @throws Exception
     */
    public HttpResult doPostJson(String url, String jsonParam) throws Exception {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");
        return this.doPost(url, jsonParam, assemblyHeader(headers));
    }

    /**
     * 带参数 发起 json post请求
     * 
     * @param url,jsonParam
     * @return
     * @throws Exception
     */
    public HttpResult doPostJson(String url, String jsonParam, Map<String, String> headers) throws Exception {
        // Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");
        return this.doPost(url, jsonParam, assemblyHeader(headers));
    }

    public HttpResult doDelete(String url, Map<String, String> headers) throws Exception {
        return this.doDelete(url, assemblyHeader(headers));
    }

    public HttpResult doGet(String url, Map<String, String> headers) throws Exception {
        return this.doGet(url, assemblyHeader(headers));
    }
}